import React, { useState, useEffect } from 'react';
import { Button, Input, Label, Text, Spinner, Table, TableHeader, TableRow, TableHead, TableBody, TableCell, Dialog, DialogContent, DialogHeader, DialogTitle, DialogDescription, DialogFooter, DialogClose, Select, Calendar, Alert, Popup, Tooltip } from 'packages/ui-shared/src/atoms';
import SchedulingAlgorithm from '../components/SchedulingAlgorithm';
import ScheduleCalendar from '../components/ScheduleCalendar';
import ScheduleTable from '../components/ScheduleTable';
import ScheduleExport from '../components/ScheduleExport';
import ScheduleConflictDetector from '../components/ScheduleConflictDetector';

// 类型定义
interface Teacher {
  id: string;
  name: string;
  availableTimeSlots: string[];
  courses: string[];
}

interface Classroom {
  id: string;
  name: string;
  capacity: number;
  equipment: string[];
  availableTimeSlots: string[];
}

interface Student {
  id: string;
  name: string;
  className: string;
  availableTimeSlots: string[];
  enrolledCourses: string[];
}

interface Course {
  id: string;
  name: string;
  teacherId: string;
  requiredStudents: string[];
  requiredClassroom: string;
  duration: number;
  priority: number;
}

interface Schedule {
  id: string;
  courseId: string;
  teacherId: string;
  classroomId: string;
  studentIds: string[];
  startTime: string;
  endTime: string;
  day: string;
}

const SchedulingManagementPage: React.FC = () => {
  // 状态管理
  const [teachers, setTeachers] = useState<Teacher[]>([]);
  const [classrooms, setClassrooms] = useState<Classroom[]>([]);
  const [students, setStudents] = useState<Student[]>([]);
  const [courses, setCourses] = useState<Course[]>([]);
  const [schedules, setSchedules] = useState<Schedule[]>([]);
  const [conflicts, setConflicts] = useState<any[]>([]);
  const [activeView, setActiveView] = useState<'day' | 'week' | 'month'>('week');
  const [currentDate, setCurrentDate] = useState<Date | null>(null);
  const [isAutoScheduling, setIsAutoScheduling] = useState(false);
  const [isModalVisible, setIsModalVisible] = useState(false);
  // 表单状态管理
  const [formData, setFormData] = useState({});
  const [editingSchedule, setEditingSchedule] = useState<Schedule | null>(null);

  // 加载数据
  useEffect(() => {
    // 模拟加载数据
    loadTeachers();
    loadClassrooms();
    loadStudents();
    loadCourses();
    loadSchedules();
  }, []);

  const loadTeachers = async () => {
    // 实际项目中这里应调用API获取教师数据
    setTeachers([
      { id: '1', name: '张教授', availableTimeSlots: ['周一上午', '周三下午'], courses: ['数学', '物理'] },
      { id: '2', name: '李老师', availableTimeSlots: ['周二全天', '周四上午'], courses: ['英语', '计算机基础'] },
    ]);
  };

  const loadClassrooms = async () => {
    // 实际项目中这里应调用API获取教室数据
    setClassrooms([
      { id: '1', name: '101教室', capacity: 50, equipment: ['投影仪'], availableTimeSlots: ['周一至周五全天'] },
      { id: '2', name: '202教室', capacity: 30, equipment: ['投影仪', '电脑'], availableTimeSlots: ['周一至周五全天'] },
    ]);
  };

  const loadStudents = async () => {
    // 实际项目中这里应调用API获取学生数据
    setStudents([
      { id: '1', name: '学生A', className: '计算机科学1班', availableTimeSlots: ['周一至周五全天'], enrolledCourses: ['数学', '计算机基础'] },
      { id: '2', name: '学生B', className: '计算机科学1班', availableTimeSlots: ['周一至周五全天'], enrolledCourses: ['数学', '英语'] },
    ]);
  };

  const loadCourses = async () => {
    // 实际项目中这里应调用API获取课程数据
    setCourses([
      { id: '1', name: '数学', teacherId: '1', requiredStudents: ['1', '2'], requiredClassroom: '1', duration: 2, priority: 1 },
      { id: '2', name: '计算机基础', teacherId: '2', requiredStudents: ['1'], requiredClassroom: '2', duration: 3, priority: 2 },
    ]);
  };

  const loadSchedules = async () => {
    // 实际项目中这里应调用API获取排课数据
    setSchedules([]);
  };

  // 智能排课功能
  // 智能排课功能
  const handleAutoSchedule = async () => {
    setIsAutoScheduling(true);
    try {
      // 简单的排课算法实现
      const newSchedules = [];
      const today = new Date();
      
      courses.forEach((course, index) => {
        const teacher = teachers.find(t => t.id === course.teacherId) || teachers[0];
        const classroom = classrooms[index % classrooms.length];
        
        // 生成时间
        const startTime = new Date(today);
        startTime.setDate(today.getDate() + index);
        startTime.setHours(9 + (index % 4) * 2); // 9:00, 11:00, 14:00, 16:00 循环
        
        const endTime = new Date(startTime);
        endTime.setHours(startTime.getHours() + Math.ceil(course.duration / 60));
        
        newSchedules.push({
          id: `schedule_${Date.now()}_${index}`,
          courseId: course.id,
          teacherId: teacher.id,
          classroomId: classroom.id,
          startTime: startTime.toISOString(),
          endTime: endTime.toISOString(),
          day: startTime.toLocaleDateString(),
          studentIds: course.requiredStudents || students.slice(0, 20).map(s => s.id)
        });
      });
      
      setSchedules(newSchedules);
      
      // 检测冲突
      const conflictDetector = new ScheduleConflictDetector(newSchedules, teachers, classrooms, students);
      const detectedConflicts = conflictDetector.detectConflicts();
      setConflicts(detectedConflicts);
      
      alert('智能排课完成');
      
      if (detectedConflicts.length > 0) {
        alert(`发现 ${detectedConflicts.length} 个冲突，请检查并手动调整`);
      }
    } catch (error) {
      alert('排课失败：' + (error as Error).message);
    } finally {
      setIsAutoScheduling(false);
    }
  };

  // 手动调整排课
  const handleEditSchedule = (schedule: Schedule) => {
    setEditingSchedule(schedule);
    setFormData({
      courseId: schedule.courseId,
      teacherId: schedule.teacherId,
      classroomId: schedule.classroomId,
      startTime: schedule.startTime ? new Date(schedule.startTime).toISOString().slice(0, 16) : '',
      endTime: schedule.endTime ? new Date(schedule.endTime).toISOString().slice(0, 16) : ''
    });
    setIsModalVisible(true);
  };

  const handleSaveSchedule = () => {
    try {
      // 验证表单数据
      if (!formData.courseId || !formData.teacherId || !formData.classroomId || !formData.startTime || !formData.endTime) {
        alert('请填写所有必填字段');
        return;
      }
      
      const updatedSchedule = {
        id: editingSchedule?.id || `schedule_${Date.now()}`,
        ...formData,
      };
      
      // 更新排课数据
      if (editingSchedule) {
        const updatedSchedules = schedules.map(s => 
          s.id === updatedSchedule.id ? updatedSchedule : s
        );
        setSchedules(updatedSchedules);
      } else {
        setSchedules([...schedules, updatedSchedule]);
      }
      
      // 重新检测冲突
      const updatedSchedules = editingSchedule ? schedules.map(s => 
        s.id === updatedSchedule.id ? updatedSchedule : s
      ) : [...schedules, updatedSchedule];
      
      const conflictDetector = new ScheduleConflictDetector(updatedSchedules, teachers, classrooms, students);
      const detectedConflicts = conflictDetector.detectConflicts();
      setConflicts(detectedConflicts);
      
      alert('排课调整成功');
      setIsModalVisible(false);
      setEditingSchedule(null);
      setFormData({});
    } catch (error) {
      alert('保存失败，请检查输入');
    }
  };

  // 导出排课结果
  const handleExportSchedule = () => {
    const exporter = new ScheduleExport(schedules, teachers, classrooms, courses);
    exporter.exportToExcel();
  };

  // 通知功能
  const handleNotifySchedule = () => {
    // 实际项目中这里应实现通知功能
    alert('已发送排课通知');
  };

  // 排课列表列定义
  const columns = [
    { title: '课程', dataIndex: 'courseId', key: 'courseId' },
    { title: '教师', dataIndex: 'teacherId', key: 'teacherId' },
    { title: '教室', dataIndex: 'classroomId', key: 'classroomId' },
    { title: '日期', dataIndex: 'day', key: 'day' },
    { title: '开始时间', dataIndex: 'startTime', key: 'startTime' },
    { title: '结束时间', dataIndex: 'endTime', key: 'endTime' },
    { title: '学生', dataIndex: 'studentIds', key: 'studentIds', render: ids => ids.join(', ') },
    { 
      title: '操作', 
      key: 'action', 
      render: (_, record) => (
        <Space size="middle">
          <Button type="text" icon={<EditOutlined />} onClick={() => handleEditSchedule(record)}>调整</Button>
          <Popconfirm title="确定要删除吗？" onConfirm={() => handleDeleteSchedule(record.id)}>
            <Button type="text" danger>删除</Button>
          </Popconfirm>
        </Space>
      ),
    },
  ];

  // 删除排课
  const handleDeleteSchedule = (id: string) => {
    const updatedSchedules = schedules.filter(s => s.id !== id);
    setSchedules(updatedSchedules);
    
    // 重新检测冲突
    const conflictDetector = new ScheduleConflictDetector(updatedSchedules, teachers, classrooms, students);
    setConflicts(conflictDetector.detectConflicts());
    
    alert('排课已删除');
  };

  // 标签页配置
  const tabItems: TabsProps['items'] = [
    {
      key: 'schedule-list',
      label: '排课列表',
      children: (
        <Card>
          <div style={{ marginBottom: 16, display: 'flex', justifyContent: 'space-between' }}>
            <Space>
              <Button type="primary" icon={<PlusOutlined />} onClick={handleAutoSchedule} loading={isAutoScheduling}>
                智能排课
              </Button>
              <Button icon={<ExportOutlined />} onClick={handleExportSchedule} disabled={schedules.length === 0}>
                导出排课
              </Button>
              <Button icon={<AlertOutlined />} onClick={() => setIsConflictModalVisible(true)} disabled={conflicts.length === 0}>
                冲突检测 ({conflicts.length})
              </Button>
              <Button icon={<EyeOutlined />} onClick={handleNotifySchedule} disabled={schedules.length === 0}>
                发送通知
              </Button>
            </Space>
            <Space>
              <Select
                value={activeView}
                onChange={(value: any) => setActiveView(value)}
                style={{ width: 120 }}
                options={[
                  { value: 'day', label: '日视图' },
                  { value: 'week', label: '周视图' },
                  { value: 'month', label: '月视图' },
                ]}
              />
              <Input
                type="date"
                value={currentDate ? currentDate.toISOString().split('T')[0] : ''}
                onChange={(e) => setCurrentDate(new Date(e.target.value))}
              />
            </Space>
          </div>
          {activeView === 'day' && <ScheduleCalendar type="day" schedules={schedules} onEdit={handleEditSchedule} />}
          {activeView === 'week' && <ScheduleCalendar type="week" schedules={schedules} onEdit={handleEditSchedule} />}
          {activeView === 'month' && <ScheduleCalendar type="month" schedules={schedules} onEdit={handleEditSchedule} />}
          <Table columns={columns} dataSource={schedules} rowKey="id" style={{ marginTop: 16 }} />
        </Card>
      ),
    },
    {
      key: 'teachers',
      label: '教师管理',
      children: <ScheduleTable title="教师列表" data={teachers} />,
    },
    {
      key: 'classrooms',
      label: '教室管理',
      children: <ScheduleTable title="教室列表" data={classrooms} />,
    },
    {
      key: 'students',
      label: '学生管理',
      children: <ScheduleTable title="学生列表" data={students} />,
    },
    {
      key: 'courses',
      label: '课程管理',
      children: <ScheduleTable title="课程列表" data={courses} />,
    },
  ];

  // 冲突检测模态框
  const [isConflictModalVisible, setIsConflictModalVisible] = useState(false);

  return (
    <div>
      <h1 style={{ marginBottom: 24 }}>排课管理</h1>
      <Tabs defaultActiveKey="schedule-list" items={tabItems} />
      
      {/* 编辑排课模态框 */}
      <Dialog
        open={isModalVisible}
        onOpenChange={setIsModalVisible}
      >
        <DialogHeader>
          <DialogTitle>{editingSchedule ? "调整排课" : "新增排课"}</DialogTitle>
        </DialogHeader>
        <DialogContent>
          <div className="space-y-4">
            <div>
              <Label htmlFor="courseId">课程</Label>
              <Select
                id="courseId"
                value={formData.courseId || ''}
                onChange={(value) => setFormData({...formData, courseId: value})}
              >
                {courses.map(course => (
                  <option key={course.id} value={course.id}>{course.name}</option>
                ))}
              </Select>
            </div>
            <div>
              <Label htmlFor="teacherId">教师</Label>
              <Select
                id="teacherId"
                value={formData.teacherId || ''}
                onChange={(value) => setFormData({...formData, teacherId: value})}
              >
                {teachers.map(teacher => (
                  <option key={teacher.id} value={teacher.id}>{teacher.name}</option>
                ))}
              </Select>
            </div>
          <div className="space-y-4">
            <div>
              <Label htmlFor="classroomId">教室</Label>
              <Select
                id="classroomId"
                value={formData.classroomId || ''}
                onChange={(value) => setFormData({...formData, classroomId: value})}
              >
                {classrooms.map(classroom => (
                  <option key={classroom.id} value={classroom.id}>{classroom.name}</option>
                ))}
              </Select>
            </div>
            <div>
              <Label htmlFor="startTime">开始时间</Label>
              <Input
                id="startTime"
                type="datetime-local"
                value={formData.startTime || ''}
                onChange={(e) => setFormData({...formData, startTime: e.target.value})}
              />
            </div>
            <div>
              <Label htmlFor="endTime">结束时间</Label>
              <Input
                id="endTime"
                type="datetime-local"
                value={formData.endTime || ''}
                onChange={(e) => setFormData({...formData, endTime: e.target.value})}
              />
            </div>
          </div>
        </DialogContent>
        <DialogFooter>
          <Button onClick={() => setIsModalVisible(false)}>取消</Button>
          <Button type="primary" onClick={handleSaveSchedule}>保存</Button>
        </DialogFooter>
      </Dialog>
      
      {/* 冲突检测结果模态框 */}
      <Dialog
        open={isConflictModalVisible}
        onOpenChange={setIsConflictModalVisible}
      >
        <DialogHeader>
          <DialogTitle>冲突检测结果 (共 {conflicts.length} 个冲突)</DialogTitle>
        </DialogHeader>
        <DialogContent>
        <Table
          columns={[
            { title: '冲突类型', dataIndex: 'type', key: 'type' },
            { title: '相关排课', dataIndex: 'schedules', key: 'schedules', render: s => s.join(', ') },
            { title: '冲突详情', dataIndex: 'detail', key: 'detail' },
            { title: '建议解决方案', dataIndex: 'solution', key: 'solution' },
          ]}
          dataSource={conflicts}
          rowKey="id"
        />
        <DialogFooter>
          <Button onClick={() => setIsConflictModalVisible(false)}>关闭</Button>
        </DialogFooter>
      </Dialog>
    </div>
  );
};

export default SchedulingManagementPage;